package com.springcloud.controller;


import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.constant.RequestRes;
import com.entity.Dep;
import com.google.gson.Gson;
import com.springcloud.service.DepService;

@RestController
public class DepController {
	
	public static final Logger log = LoggerFactory.getLogger(DepController.class);
	
	@Autowired
	private DepService depService;
		
	
	// 作用是 自测 自己注册的服务是否可用
	@Autowired
	private DiscoveryClient client;
	
	
	@RequestMapping(value="/{depno}")
	@ResponseBody
	public RequestRes queryById(@PathVariable("depno") Integer depno){
		log.info("queryById start!!! depno is {}",depno);	
		Dep dep = depService.queryDepByDepNo(depno);
		if(dep!=null){
			return RequestRes.ReSuccess(new Gson().toJson(dep));
		}
		return RequestRes.ReError();
	}
	
	@RequestMapping(value="/list",method=RequestMethod.GET)
	@ResponseBody
	public RequestRes queryAll(){
		log.info("queryAll start!!!");	
		List<Dep> list = depService.queryAll();
		if(!CollectionUtils.isEmpty(list)){
			return RequestRes.ReSuccess(new Gson().toJson(list));
		}
		return RequestRes.ReError();
	}
	
	
	/**
	 * 测试自己的服务是否可以调用，如果调用成功，则再SpringCloud-consumer 上调用
	 * @return
	 */
	@RequestMapping(value="/discover",method=RequestMethod.GET)
	@ResponseBody
	public RequestRes getDiscover(){
		log.info("getDiscover start!!!");	
		// 获取所有的服务
		List<String> serList = client.getServices();
		if(CollectionUtils.isEmpty(serList)){
			return RequestRes.ReError();
		}
		log.info("Eureka 注册的服务个数为 {} ", serList.size());
		// 获取服务实例
		List<ServiceInstance> instances = client.getInstances("SpringCloud-provider");
		instances.forEach(service->{
			log.info("微服务的 IP 是 {}, 端口号是 {} , 服务 Id 是  {}",service.getHost(),service.getPort(),service.getServiceId());
		});
		return RequestRes.ReSuccess(instances);
	}
	
}
